package top.ranzhang.interceptor;


import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import top.ranzhang.common.context.BaseContext;
import top.ranzhang.common.properties.JwtProperties;
import top.ranzhang.constant.JwtClaimsConstant;
import top.ranzhang.utils.JwtUtil;

@Slf4j
@Component
public class JwtTokenAdminInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中的令牌
        String token = request.getHeader(jwtProperties.getAdminTokenName());
        log.info("token:{}",token);
        // 判断令牌是否存在
        if(token == null){
            response.setStatus(401);
            return false;
        }
        try {
            // 解析令牌
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
            Long EmpId = Long.valueOf(claims.get(JwtClaimsConstant.Employee_ID).toString());
            // 将员工id存入当前线程中
            BaseContext.setCurrentId(EmpId);
            log.info("当前员工id为:{}",EmpId);
            return true;
        }catch (Exception e){
            // 令牌解析失败
            response.setStatus(401);
            return false;
        }
    }
}
